package com.fzg.common.tool;

import com.alibaba.fastjson.JSONObject;
import com.fzg.common.enums.ResponseWrapper;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

import static cn.hutool.core.lang.Console.log;

/**
 * json相关的公共方法
 * create by fzg
 * 2022/8/19 10:38
 */

@Slf4j
public class JSONUtilsTool {

    /**
     * JSONObject转map
     * @param jsonObject 参数：JSON对象
     * @return map对象
     */
    public static Map<String,Object> JSONObjectToMap(JSONObject jsonObject){
        if (jsonObject.isEmpty()){
            return new HashMap<>();
        }else {
            HashMap<String, Object> map = new HashMap<>();
            for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
                map.put(entry.getKey(), entry.getValue());
            }
            log("map对象:" + map);
            if (map.size() > 0){
                return map;
            }else {
                return new HashMap<>();
            }
        }
    }


    /**
     * JSONObject转map
     * @param jsonObject 参数：JSON对象
     * @return ResponseWrapper对象
     */
    public static ResponseWrapper JSONObjectToMapReturnResponseWrapper(JSONObject jsonObject){
        if (jsonObject.isEmpty()){
            return ResponseWrapper.markError();
        }else {
            HashMap<String, Object> map = new HashMap<>();
            for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
                map.put(entry.getKey(), entry.getValue());
            }
            log("map对象:" + map);
            if (map.size() > 0){
                if(!map.get("code").equals(200)){
                    return ResponseWrapper.markCustomError(map.get("msg").toString());
                }else {
                    return ResponseWrapper.markSuccess(map.get("data"));
                }
            }else {
                return ResponseWrapper.markError();
            }
        }
    }

}
